package com.mac.bluetoothbt.feature;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.List;
import java.util.Map;

public class BleAdapter extends SimpleAdapter {
    List<? extends Map<String, ?>> data;
    Context context;

    public BleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
        
        super(context, data, resource, from, to);
        this.data = data;
        this.context = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.ble_list_item, parent, false);
        }
        TextView uptext = get(convertView, R.id.up_text);
        TextView downtext = get(convertView, R.id.down_text);
        ImageView his = get(convertView, R.id.img_his);

        Map<String, ?> map = data.get(position);

        String name = (String)map.get("name");
        String mac = (String)map.get("mac");
        boolean add = false;
        Object a = map.get("added");
        if (a != null) {
            add = (Boolean) a;
        }

        uptext.setText(name);
        downtext.setText(mac);
        if (add) {
            //his.setImageResource(R.drawable.ic_history_black_24dp);
            his.setImageDrawable(context.getDrawable(R.drawable.ic_history_black_24dp).mutate());
        }  else {
            his.setImageDrawable(null);
        }
        return convertView;
    }

    public static <T extends View> T get(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }
        View childView = viewHolder.get(id);
        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }

}
